package com.yang.String_;

public class LeetCode151 {
    public static void main(String[] args) {
        SolutionLeetCode151 solutionLeetCode151 = new SolutionLeetCode151();
//        StringBuilder s= new StringBuilder("12 2345 63");
        String s = "  hello world  ";
        System.out.println(s);
        String s1 = solutionLeetCode151.reverseWords(s);
        System.out.println(s1);
    }
}

// 拆分为几部分来做，一部分是去掉空格 采用快慢指针的方法 一部分就是反转字符串
class SolutionLeetCode151 {
    public String reverseWords(String s) {
        StringBuilder stringBuilder = removeSpace(s);
        reverseString(stringBuilder, 0, stringBuilder.length()-1);
        reverseEachWord(stringBuilder);
        return new String(stringBuilder);
    }

    public void reverseString(StringBuilder s, int start, int end){
        while (end > start){
            char temp = s.charAt(start);
            s.setCharAt(start, s.charAt(end));
            s.setCharAt(end, temp);
            end--;
            start++;
        }
    }

    public void reverseEachWord(StringBuilder s){
        int start = 0;
        int end = 1;
        int length = s.length();
        while (end < length){
            while (end!=length && s.charAt(end) != ' '){
                end++;
            }
            reverseString(s, start, end-1);
            start = end + 1;
            end += 1;
        }
    }

    private StringBuilder removeSpace(String s){
        int start = 0;
        int end = s.length() - 1;
        StringBuilder stringBuilder = new StringBuilder();
        while (s.charAt(start) == ' ') start++;
        while (s.charAt(end) == ' ') end--;

        // 注意边界问题！！！！！！！ 这里的start必须是小于end  而不是 length 那样就会越界end甩掉的空格
        while (start <= end){
            char c = s.charAt(start);
            if(c != ' ' || stringBuilder.charAt(stringBuilder.length()-1) != ' '){
                stringBuilder.append(c);
            }
            start++;
        }
        return stringBuilder;
    }
}
